/**
 * @author Mustafa K. Isik
 */

import toys.base.*;
import toys.compiler.example.*;

public class ParserExerciseThree extends StringFormParser{
	private char currentToken;
	private int currentResultIndex = 0;

	public void parse() throws SyntaxError{
		start('E'); 					//specify startsymbol
		currentToken = getNextToken(); 	//read first token from input
		E();							//parse for startsymbol
		advanceForTerminal('$'); 		//advance processing for expected terminal, compare to read token				
	}

	/**
	 * Realizes the "E" productions of grammar G1 on exercise sheet 5.
	 * 
	 * E -> "(" E O E ")"
	 * E -> "n"
	 * E -> "i"
	 */
	private void E() throws SyntaxError{
		switch(currentToken){
		case '(':
		{
			replace(currentResultIndex, "(EOE)");
			advanceForTerminal('(');
			E();
			O();
			E();
			advanceForTerminal(')');
			break;
		}
		case 'n':
		{
			replace(currentResultIndex, "n");
			advanceForTerminal('n');
			break;
		}
		case 'i':
		{
			replace(currentResultIndex, "i");
			advanceForTerminal('i');
			break;
		}
		default:
			throw new SyntaxError("unexpected input: " + currentToken);
		}
	}
	/**
	 * Realizes the "O" productions from the grammar G1 on exercise sheet 5.
	 * 
	 * O -> "+"
	 * O -> "*"
	 * 
	 */
	private void O() throws SyntaxError{
		switch(currentToken){
		case '+':
		{
			replace(currentResultIndex, "+");
			advanceForTerminal('+');
			break;
		}
		case '*':
		{
			replace(currentResultIndex, "*");
			advanceForTerminal('*');
			break;
		}
		default: 
			throw new SyntaxError("unexpected input: " + currentToken);
		}
	}

	private void advanceForTerminal(char toBeEqual) throws SyntaxError{
		if(currentToken == toBeEqual){
			currentResultIndex++;
			currentToken = getNextToken();			
		}else{
			throw new SyntaxError("unexpected input: passed " + currentToken + ", instead of " + toBeEqual);
		}
	}

}
